#include <iostream>
#include <cerrno>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

int main(int argc, char*argv[])
{
    {
        if(argc != 3)
        {
            cout << "Useage: \n\t" << "server_ip server_port" << endl;
            return 1;
        }
    }
    string svr_ip = argv[1];
    uint16_t svr_port = (uint16_t)atoi(argv[2]);

    //1.创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        cerr << "socket error: " << errno << endl;
        return 2;
    }

    //2.bind, 3.listen, 4.accept
    ///client无需显示的绑定，client->server
    //client->connect!
    //connect成功时系统自动绑定
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(svr_port);
    server.sin_addr.s_addr = inet_addr(svr_ip.c_str());
    //发起连接
    if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        cerr << "connect server failed ! " << errno << endl;
        return 3; 
    }

    cout << "connect success !" << endl;

    while(true)
    {
        char buffer[1024];
        cout << "Please Enter# ";
        fgets(buffer, sizeof(buffer) - 1, stdin);

        write(sock, buffer, strlen(buffer));

        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << "server echo# " << buffer << endl;
        }
    }

    return 0;
}